package it.antonio.ilpizze.db;

import it.antonio.ilpizze.db.core.Types;
import it.antonio.ilpizze.db.io.IOConstants;
import it.antonio.ilpizze.func.Pair;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public final class Record implements Iterable<Pair<String, Object>>, IOConstants {

	private List<Pair<String,Object>> records = new LinkedList<Pair<String,Object>>();
	private Map<String, Object> recordMap = new HashMap<String, Object>();
	
	private int size;
	
	public void put(String s, Object v){
		size+= SIZE_INT + s.length(); // key size 
		size++; // type byte
		size += Types.size(v);
		
		records.add(Pair.from(s, (Object)v));
		recordMap.put(s, v);
	}
	
	
	

	@SuppressWarnings("unchecked")
	public <T> T get(String key){
		Object returnObj = recordMap.get(key); 
		try{
			return (T) returnObj; 
		} catch (ClassCastException e) {
			throw new DbException("Cast exception: " + e.getMessage());
		}
	}
	
	
	public int size(){
		return size;
	}
	
	@Override
	public Iterator<Pair<String, Object>> iterator() {
		return records.iterator();
	}

}
